/*
 * Java Card File Parser 
 * Based on openjcvm project 
 */
package org.naive.metawatch.converter.parser;

import java.nio.charset.Charset;
import java.text.ParseException;

/**
 *
 * @author Andrew Butenko
 */
public class ParseContext {

    private byte[] data;
    private int offset;

    public ParseContext(byte[] data) {
        this.data = data;
        this.offset = 0;
    }

    public int makeInt(int startPos) {
        int p = startPos + offset;
        return (0xFF & data[p] << 24)
                | (0xFF & data[p + 1] << 16)
                | (0xFF & data[p + 2] << 8)
                | (0xFF & data[p + 3]);
    }

    public byte readByte() {
        return data[offset++];
    }

    public short readShort() {
        final short v = (short) ((0xFF & data[offset]) << 8 | (0xFF & data[offset + 1]));
        offset += 2;
        return v;
    }

    public int readInt() {
        final int v = (0xFF & data[offset] << 24)
                | (0xFF & data[offset + 1] << 16)
                | (0xFF & data[offset + 2] << 8)
                | (0xFF & data[offset + 3]);
        offset += 4;
        return v;
    }

    public Number read(FieldSize z) throws ParseException {
        switch (z) {
            case BYTE:
                return readByte();
            case SHORT:
                return readShort();
            case INT:
                return readInt();
        }
        throw new ParseException("Unsupported field size", getOffset());
    }

    public int readU(FieldSize z) throws ParseException {
        switch (z) {
            case BYTE:
                return readByte() & 0xFF;
            case SHORT:
                return readShort() & 0xFFFF;
        }
        throw new ParseException("Unsupported field size", getOffset());
    }

    public String readUtf8(int len) {
        final String v = new String(data, offset, len, Charset.forName("UTF-8"));
        offset += len;
        return v;
    }

    public void setOffset(int newOffset) {
        offset = newOffset;
    }

    public int getOffset() {
        return offset;
    }

    public void advanceOffset(int delta) {
        offset += delta;
    }

    @Override
    public String toString() {
        return "Parse Context:" + offset;
    }
}
